<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="70px">
      <el-form-item label="文章名称" prop="artName">
        <el-input v-model="queryParams.artName" placeholder="请输入文章名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="文章类别" prop="categoryId">
        <el-select v-model="queryParams.categoryId" clearable placeholder="请选择文章类别" width="100%" @change="handleQuery">
          <el-option v-for="item in articleCategoryList" :key="item.id" :label="item.cateName" :value="item.id" :disabled="item.categoryStatus == 0">
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['information:article:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['information:article:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['information:article:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column label="文章首图" align="center" prop="indexImg">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.indexImg" fit="fit"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="文章名称" align="center" prop="artName" />
      <el-table-column label="作者" align="center" prop="author" />
      <el-table-column label="来源" align="center" prop="source" />
      <el-table-column label="文章类别" align="center" prop="categoryId">
        <template slot-scope="scope">
          <span>{{ changeCategoryId(scope.row.categoryId
    ) }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="发布时间" align="center" prop="releaseTime" />-->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['information:article:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row,scope.$index)"
            v-hasPermi="['information:article:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改文章管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="文章首图" prop="indexImg">
          <el-upload class="avatar-uploader" action :http-request="selectPicUpload" :show-file-list="false">
            <img v-if="form.indexImg" :src="form.indexImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章名称" prop="artName">
          <el-input v-model="form.artName" placeholder="请输入文章名称" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入来源" />
        </el-form-item>
<!--        <el-form-item label="发布时间" prop="releaseTime">-->
<!--          <el-date-picker-->
<!--            v-model="form.releaseTime"-->
<!--            type="datetime"-->
<!--            placeholder="选择日期时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
        <el-form-item label="文章类别" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择文章类别" width="100%">
            <el-option v-for="item in articleCategoryList" :key="item.id" :label="item.cateName" :value="item.id">
            </el-option>
          </el-select>
          <!-- <el-input v-model="form.categoryId" placeholder="请输入文章类别id" /> -->
        </el-form-item>
        <el-form-item label="文章摘要" prop="articleAbstract">
          <el-input v-model="form.articleAbstract" placeholder="请输入文章摘要" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="文章内容" prop="contentId">
          <tinymce v-if="open" v-model="form.content" style="" :height="500" :img-base-url="imgUrl" />
        </el-form-item>
        <!-- <el-form-item label="所属地区" prop="area">
          <el-input v-model="form.area" placeholder="请输入所属地区" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArticle, getArticle, delArticle, addArticle, updateArticle } from "@/api/information/article";
import { listArticleCategory } from "@/api/information/articleCategory";
import { imgUrl } from '@/utils/request'
import Tinymce from '@/components/Tinymce'
import { uploadPic } from '@/api/supermarket/product'

export default {
  name: "Article",
  components: {
    Tinymce
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章管理表格数据
      articleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        artName: null,
        categoryId: null,
        articleStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //图片拼接头
      imgUrl: imgUrl,
      //  文章类别列表
      articleCategoryList: [],
      //商品介绍图片上传
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
    };
  },
  created() {
    this.getList();
    // this.changeParams()
  },
  methods: {
    /** 查询文章管理列表 */
    async getList() {
      this.loading = true;
      await listArticle(this.queryParams).then(response => {
        this.articleList = response.pageData;
        this.total =Number(response.total);
        this.changeParams()
        this.loading = false;
      });
    },
    // 查询文章列表
    changeParams() {
      listArticleCategory().then(response => {
        if (response.code == 200) {
          this.articleCategoryList = response.pageData
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        source:'',
        releaseTime:'',
        id: null,
        indexImg: null,
        artName: null,
        author: null,
        categoryId: null,
        createTime: null,
        articleAbstract: null,
        contentId: null,
        articleStatus: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getArticle(id).then(response => {
        console.log(response.data)
        this.form = response.data;
        this.open = true;
        this.title = "修改文章管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateArticle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArticle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row,id) {
      const ids = (id+1) || this.ids;
      const delIds=row.id ||this.ids
      this.$modal.confirm('是否确认删除文章管理编号为"' + ids + '"的数据项？').then(function () {
        return delArticle(delIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('information/article/export', {
        ...this.queryParams
      }, `article_${new Date().getTime()}.xlsx`)
    },
    // 转化文章类别
    changeCategoryId(type) {
      for (let i = 0; i < this.articleCategoryList.length; i++) {
        if (this.articleCategoryList[i].id == type) {
          return this.articleCategoryList[i].cateName
        }
      }
    },
    //上传商品图片
    selectPicUpload(obj) {

      let fd = new FormData() //参数的格式是formData格式的
      fd.append('file', obj.file) //参数
      console.log(fd)
      uploadPic(fd, { modularName: 'ARTICLE' }).then(res => {
        this.form.cover = res
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg/png/jpg';
      const isLt2M = file.size / 1024 / 1024 < 1;
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 1MB!');
      // }
      return isJPG && isLt2M;
    },
    //商品介绍图片
    selectPicListUpload(obj) {
      let fd = new FormData(); //参数的格式是formData格式的
      fd.append("productImg", obj.file); //参数
      uploadPic(fd).then(res => {
        this.form.imgUrl.push(res.msg);
        this.fileList.push({
          name: 'image', url: this.imgUrl + res.msg
        })
      });
    },
    //移除图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
      //拿到删除索引
      let index = this.fileList.indexOf(file)
      this.form.imgUrl.slice(index, 1)
      const list = JSON.parse(JSON.stringify(fileList))
      this.fileList = list.map(item => ({
        name: item.name,
        url: item.url
      }))
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加协议列表'
    },
    // 文章状态修改
    changeStatus(row) {
      console.log(row)
      this.form.articleStatus =row.articleStatus
      this.form.id = row.id
      changeArticleStatus(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      });
    }
  }
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
